package com.fox.lazy.config;

import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.util.StringUtils;

import org.springframework.core.env.Environment;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.UUID;

/**
 * 日志放入相关参数 方便日志跟踪
 *
 * @author 何杰
 */
@Order(0)
@Configuration
@WebFilter(filterName = "logFilter", urlPatterns = {"*"})
public class LogFilter implements Filter {
    final String traceKey = "trace-id";

    @Autowired
    private Environment env;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //获取请求链路 通过请求头 trace-id
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String appName = env.getProperty("spring.application.name");
        if (!StringUtils.isEmpty(appName)) {
            MDC.put("service", appName);
        }
        String active = env.getProperty("spring.profiles.active");
        if (!StringUtils.isEmpty(active)) {
            MDC.put("active", active);
        }
        String traceId = request.getHeader(traceKey);
        if (StringUtils.isEmpty(traceId)) {
            traceId = UUID.randomUUID().toString().replace("-", "");
        }
        MDC.put(traceKey, traceId);
        try {
            filterChain.doFilter(servletRequest, servletResponse);
        } finally {
            MDC.remove(traceKey);
        }
    }
}
